package com.richbond.sdjdsm;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.richbond.sdjdsm.bean.OrderBean;
import com.richbond.sdjdsm.bean.UpdateBean;
import com.richbond.sdjdsm.common.BaseActivity;
import com.richbond.sdjdsm.dao.OrderDao;
import com.richbond.sdjdsm.util.DialogHelper;
import com.richbond.sdjdsm.util.JsonUtil;
import com.richbond.sdjdsm.util.StringUtils;
import com.richbond.sdjdsm.util.UIHelp;
import com.richbond.sdjdsm.util.update.UpdateManager;
import com.richbond.sdjdsm.webserver.PoiWS;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

/**
 * Created by liwenxun on 15/9/6.
 */
public class NotSubmittedActivity extends BaseActivity {

    private static final String TAG = NotSubmittedActivity.class.getSimpleName();
    private PoiWS ws;
    private ListView listView;
    private TextView tv_tips;
    private LayoutInflater inflater;
    private PropagandaAdapter adapter;

    public OrderDao orderDao = new OrderDao(this);
    private List<OrderBean> list = null;
    private OrderBean orderBean = null;//当前用户点击的快件信息
    private boolean isTask = false;
    private HashMap<String, String> mHashMap;


    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setBaseContentLayout(R.layout.activity_propaganda);
        init();
    }

    @Override
    public void onResume() {
        super.onResume();
        list = null;
        list = orderDao.findData(OrderDao.STATUS_NO);
        if (list.size() > 0) {
            orderBean = list.get(0);
        } else {
            orderBean = new OrderBean();
        }
        tv_tips.setText(list.size() > 0 ? list.size() + "" : "0");
        Log.e("list ===", list.toString());
        adapter.notifyDataSetChanged();
    }


    private void init() {
        setTitle("未提交快递");
        ws = new PoiWS(this);
        setRightBtn("提交", R.color.transparent, 80, 50);

        list = orderDao.findData(OrderDao.STATUS_NO);

        listView = (ListView) findViewById(R.id.listView);
        tv_tips = (TextView) findViewById(R.id.tv_tips);

        tv_tips.setText(list.size() > 0 ? list.size() + "" : "0");
        adapter = new PropagandaAdapter(this);
        listView.setAdapter(adapter);
        inflater = LayoutInflater.from(this);
    }


    @Override
    protected void onRightClick(View v) {

        if (UIHelp.isNetworkConnected(this)) {
            if (list.size() > 0) {
                if (isTask) {
                    Log.i("isTask=========", "true");
                    return;
                }
                isTask = true;
                new UpdateTask().execute();
            } else {
                DialogHelper.showToast(NotSubmittedActivity.this, "没有需要提交的快递内容！");
            }
        } else {
            DialogHelper.showToast(NotSubmittedActivity.this, "没有网络，无法提交！");

        }

    }

    class PropagandaAdapter extends BaseAdapter {
        private Context ct;


        public PropagandaAdapter(Context context) {
            super();
            this.ct = context;

        }

        @Override
        public int getCount() {
            if (list.size() > 0) {
                return list.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = null;
            view = inflater.inflate(R.layout.item_submitted, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            TextView tv_customer_phone = (TextView) view.findViewById(R.id.tv_customer_phone);
            TextView tv_barcode = (TextView) view.findViewById(R.id.tv_barcode);

            final LinearLayout ll_go = (LinearLayout) view.findViewById(R.id.ll_go);
            ll_go.setTag(position);

            tv_name.setText("客户姓名：" + StringUtils.getHideCharacter(list.get(position).getCustomname()));
            tv_customer_phone.setText("客户手机：" + StringUtils.getHideCharacter(list.get(position).getCustomphone()));
            tv_barcode.setText("物流单号：" + list.get(position).getBarcode());

            ll_go.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int tag = Integer.parseInt(v.getTag().toString());
                    goToContent(tag);
                }
            });
            return view;
        }
    }

    public void goToContent(int tag) {
        Bundle bundle = new Bundle();
        bundle.putString("barcode", list.get(tag).getBarcode());
        openActivity(NotSubmittedInfoActivity.class, bundle);
    }

    /**
     * 获取更新的异步任务
     */
    private class UpdateTask extends AsyncTask<String, String, JSONObject> {
        @Override
        protected JSONObject doInBackground(String... params) {
            return ws.Update();
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            Log.v("获取更新的json---result=======", String.valueOf(result));
            if (JsonUtil.GetJsonStatu(result)) {
                final UpdateBean updateBean = new UpdateBean();
                try {
                    JSONObject jsonObject = result.getJSONObject("data");
                    updateBean.setAppVersionCode(jsonObject.getString("appVersionCode"));
                    updateBean.setAppVersionName(jsonObject.getString("appVersionName"));
                    updateBean.setAppDownloadUrl(jsonObject.getString("appDownloadUrl"));
                    updateBean.setWebInterface(jsonObject.getString("webInterface"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                UpdateManager manager = new UpdateManager(NotSubmittedActivity.this, updateBean);
                if (manager.isUpdate()) {
                    DialogHelper.closeProgressDialog();
                    // 显示提示对话框
                    DialogHelper.showToast(NotSubmittedActivity.this, "请在设置中更新到最新版本,否则无法使用!");
                    isTask = false;
                } else {
                    new SendInfo().execute(orderBean);
                }
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogHelper.showProgressDialog(NotSubmittedActivity.this, "正在提交...");
        }
    }

    class SendInfo extends AsyncTask<OrderBean, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(OrderBean... params) {
            return ws.sendInfo(params[0]);
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);

            Log.i("SendInfo=======", String.valueOf(result));
            if (JsonUtil.GetJsonStatu(result)) {
                orderDao.updateStatus(list.get(0).getBarcode(), OrderDao.STATUS_YES);

                list = null;
                list = orderDao.findData(OrderDao.STATUS_NO);
                adapter.notifyDataSetChanged();
                if (list.size() > 0) {
                    orderBean = list.get(0);
                } else {
                    isTask = false;
                    onResume();
                    DialogHelper.closeProgressDialog();
                    DialogHelper.showToast(NotSubmittedActivity.this, "已提交成功！");
                }
            } else {
                isTask = false;
                DialogHelper.showToast(NotSubmittedActivity.this, JsonUtil.GetString(result, "msg"));
                DialogHelper.closeProgressDialog();
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogHelper.showProgressDialog(NotSubmittedActivity.this, "正在提交...");
        }
    }
}
